// 用户数据管理功能
function initUserDataPage() {
    console.log('初始化成员数据管理页面');

    // 检查 Supabase 是否初始化
    if (!supabase) {
        console.error('Supabase 未初始化');
        const messageDiv = document.getElementById('message');
        if (messageDiv) {
            showMessage(messageDiv, '系统初始化失败，请刷新页面', 'error');
        }
        return;
    }

    // 获取DOM元素

    const seachName = document.getElementById('seach-name');

    const searchBtn = document.getElementById('search-btn');
    const clearSearchBtn = document.getElementById('clear-search');
    const idCardNumber = document.getElementById('id-card-number');
    const messageDiv = document.getElementById('message');
    const userAvatar = document.getElementById('user-avatar');
    const userDisplayName = document.getElementById('user-display-name');

    const userEmail = document.getElementById('user-email');

    // 数据管理相关元素
    const addDataBtn = document.getElementById('add-data-btn');
    const refreshBtn = document.getElementById('refresh-btn');
    const userDataTbody = document.getElementById('user-data-tbody');
    const userDataTable = document.getElementById('user-data-table');
    const loadingIndicator = document.getElementById('loading-indicator');
    const noDataMessage = document.getElementById('no-data-message');
    const dataCount = document.getElementById('data-count');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const pageInfo = document.getElementById('page-info');
    const pagination = document.getElementById('pagination');

    // 模态框相关元素
    const dataModal = document.getElementById('data-modal');
    const deleteModal = document.getElementById('delete-modal');
    const closeModalBtn = document.getElementById('close-modal');
    const closeDeleteModalBtn = document.getElementById('close-delete-modal');
    const dataForm = document.getElementById('data-form');
    const cancelBtn = document.getElementById('cancel-btn');
    const saveDataBtn = document.getElementById('save-data-btn');
    const cancelDeleteBtn = document.getElementById('cancel-delete');
    const confirmDeleteBtn = document.getElementById('confirm-delete');

    // 分页状态
    let currentPage = 1;
    const pageSize = 10;
    let totalCount = 0;
    let currentFilters = {};

    // 添加数据按钮
    if (addDataBtn) {
        addDataBtn.addEventListener('click', () => {
            openAddModal();
        });
    }

    // 刷新数据按钮
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            currentPage = 1;
            loadUserData();
        });
    }

    // 搜索按钮
    if (searchBtn) {
        searchBtn.addEventListener('click', () => {
            currentPage = 1;
            applyFilters();
        });
    }

    // 清除搜索
    if (clearSearchBtn) {
        // document.getElementById('seach-id-card-number').value = '';
        clearSearchBtn.addEventListener('click', () => {
            currentPage = 1;
            currentFilters = {};
            loadUserData();
        });
    }

    // 分页按钮
    if (prevPageBtn) {
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                loadUserData();
            }
        });
    }

    if (nextPageBtn) {
        nextPageBtn.addEventListener('click', () => {
            if (currentPage * pageSize < totalCount) {
                currentPage++;
                loadUserData();
            }
        });
    }

    // 模态框控制
    if (closeModalBtn) closeModalBtn.addEventListener('click', closeModal);
    if (closeDeleteModalBtn) closeDeleteModalBtn.addEventListener('click', closeDeleteModal);
    if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
    if (cancelDeleteBtn) cancelDeleteBtn.addEventListener('click', closeDeleteModal);

    // 保存数据表单
    if (dataForm) {
        dataForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await saveUserData();
        });
    }

    // 确认删除
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', async () => {
            await deleteUserData();
        });
    }

    // 显示用户信息
    function showUserInfo(user) {
        showUserInfoCommon(user, userEmail, userDisplayName, userAvatar);
    }
    async function getSelectById(userid){
        /**/
        let query = supabase
            .from('hc_dnodes')
            .select('id,name')
            .eq('is_deleted', false) ;
        const { data, error, count } = await  query;
        if (data.length>0){
            const select = document.getElementById('dnode-id');
            data.forEach(dept => {
                const option = new Option(dept.name, dept.id);
                select.add(option);
            });
        }
        if (error) {
            throw error;
        }
    }
    async function getProIdAndName(){
        /**/
        let query = supabase
            .from('hc_user_profiles')
            .select('id,username')
            .eq('is_deleted', false) ;
        const { data, error, count } = await  query;
        if (data && data.length>0){
            const select = document.getElementById('user-id');  //
            data.forEach(dept => {
                const option = new Option(dept.username, dept.id);
                select.add(option);
            });
        }
        if (error) {
            throw error;
        }
    }
    async function getRoleAndName(){
        let query = supabase
            .from('hc_dnode_roles')
            .select('id,role_type,name')
            .eq('is_deleted', false) ;
        const { data, error, count } = await  query;
        if (data && data.length>0){
            const selectTwo = document.getElementById('role');  //
            data.forEach(dept => {
                const option = new Option(dept.name, dept.role_type);
                selectTwo.add(option);
            });
        }
        if (error) {
            throw error;
        }
    }
    // 加载用户数据
    async function loadUserData() {
        const { data: userData, error: userError } = await supabase.auth.getUser();
        if (userError || !userData.user) {
            showMessage(messageDiv, '用户未登录', 'error');
            window.location.href = '../hc_login/index.html';
            return;
        }

        showLoading(true);

        try {


    /*        const { data, error } = await supabase
                .from('hc_dnode_members')
                .select(`*,
    hc_user_profiles (*)
  `);*/
            let query = supabase
                .from('hc_dnode_members')
                .select('*,hc_user_profiles(username), hc_dnodes!fk_hc_dnode_members_dnode_id(name)', { count: 'exact' },)
                .eq('is_deleted', false)
                .eq('dnode_id',document.getElementById('dnodesId').value)
                .range((currentPage - 1) * pageSize, currentPage * pageSize - 1);

            // 应用筛选条件
            if (currentFilters.name) {
                query = query.eq('hc_user_profiles.username', `${currentFilters.name}`);
            }
           const { data, error, count } = await query;

            if (error) {
                throw error;
            }

            totalCount = count || 0;
            displayUserData(data || []);
            updatePagination();
            updateDataCount();

        } catch (error) {
            console.error('加载用户数据错误:', error);
            showMessage(messageDiv, '加载数据失败: ' + error.message, 'error');
        } finally {
            showLoading(false);
        }
    }

    // 显示用户数据
    function displayUserData(data) {
        const tbody = userDataTbody;
        if (!tbody) return;

        tbody.innerHTML = '';

        if (data.length === 0) {
            userDataTable.classList.add('hidden');
            noDataMessage.classList.remove('hidden');
            pagination.classList.add('hidden');
            return;
        }

        userDataTable.classList.remove('hidden');
        noDataMessage.classList.add('hidden');
        pagination.classList.remove('hidden');

        data.forEach(item => {
            const row = document.createElement('tr');

            // 格式化 JSON 数据显示
            const dataStr = item.permissions ? JSON.stringify(item.permissions) : '{}';
            const dataPreview = dataStr.length > 50 ?
                dataStr.substring(0, 50) + '...' : dataStr;
            row.innerHTML = `
                <td  class="hidden">${item.id}</td>
                <td >${item.hc_dnodes.name}</td>
                <td>${item.hc_user_profiles.username}</td>
                <td>${item.role}</td> 
                <td><span class="json-preview" title="${dataPreview }">${dataPreview }</span></td>  
                <td class="actions">
                    <button class="btn btn-sm btn-outline"  onclick="editUserData('${item.id}')">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="confirmDelete('${item.id}')">删除</button>
                </td>
            `;

            tbody.appendChild(row);
        });
    }

    // 更新分页信息
    function updatePagination() {
        if (!pageInfo) return;

        const totalPages = Math.ceil(totalCount / pageSize);
        pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;

        prevPageBtn.disabled = currentPage <= 1;
        nextPageBtn.disabled = currentPage >= totalPages;
    }

    // 更新数据计数
    function updateDataCount() {
        if (dataCount) {
            dataCount.textContent = totalCount;
        }
    }

    // 显示/隐藏加载指示器
    function showLoading(show) {
        if (loadingIndicator) {
            if (show) {
                loadingIndicator.classList.remove('hidden');
                userDataTable.classList.add('hidden');
                noDataMessage.classList.add('hidden');
                pagination.classList.add('hidden');
            } else {
                loadingIndicator.classList.add('hidden');
            }
        }
    }

    // 应用筛选条件
    function applyFilters() {
        currentFilters = {
            name: seachName ? seachName.value.trim() : '',
        };
        loadUserData();
    }

    // 打开添加模态框
    function openAddModal() {

        const modalTitle = document.getElementById('modal-title');
        const dataForm = document.getElementById('data-form');

        if (modalTitle) modalTitle.textContent = '添加组织数据';
        if (dataForm) {
            dataForm.reset();
            // 确保清空隐藏字段
            document.getElementById('uu-id').value = '';
        }
        dataModal.classList.remove('hidden');
        let  b =document.getElementById('dnodesId').value;
        document.getElementById('dnode-id').value=b;
    }

    // 关闭模态框
    function closeModal() {
        dataModal.classList.add('hidden');
    }

    function closeDeleteModal() {
        deleteModal.classList.add('hidden');
    }

    // 保存用户数据
    async function saveUserData() {
        const { data: userData, error: userError } = await supabase.auth.getUser();
        if (userError || !userData.user) {
            showMessage(messageDiv, '用户未登录', 'error');
            return;
        }
        const uuid = document.getElementById('uu-id').value;
        const dnodeid = document.getElementById('dnode-id').value; //组织
        const userid = document.getElementById('user-id').value;  //成员

        const select = document.getElementById('role');
        const index = select.selectedIndex; // 获取选中项索引
        const value = select.options[index].value; // 通过options集合获取值  type
        const text = select.options[index].text; // 获取选项的显示文本:ml-citation{ref="7" data="citationList"}     中文


        const permissions = document.getElementById('permissions').value;  //自定义权限

        // 验证必填字段
        if ( !dnodeid || !userid  || !role) {
            showMessage(messageDiv, '请填写所有必填字段', 'error');
            return;
        }
        // 验证 JSON 格式
        let parsedData;
        try {
            parsedData = permissions ? JSON.parse(permissions) : {};
        } catch (error) {
            showMessage(messageDiv, 'JSON 格式错误: ' + error.message, 'error');
            return;
        }

        try {
            setButtonLoading(saveDataBtn, true);

            const userDataObj = {
                //id: userData.user.id,
                dnode_id: dnodeid,
                user_id: userid,
                role:value,
                permissions:parsedData,
             //   updated_at: new Date().toISOString()
            };


            let result;
            if (uuid) {
                // 更新现有数据
                result = await supabase
                    .from('hc_dnode_members')
                    .update(userDataObj)
                    .eq('id', uuid);
            } else {
                // 插入新数据
                result = await supabase
                    .from('hc_dnode_members')
                    .insert([userDataObj]);
            }

            const { error } = result;

            if (error) {
                throw error;
            }

            closeModal();
            loadUserData();
            showMessage(messageDiv, uuid ? '数据更新成功！' : '数据添加成功！', 'success');

        } catch (error) {
            console.error('保存组织数据错误:', error);
            showMessage(messageDiv, '保存失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(saveDataBtn, false);
        }
    }

    // 编辑用户数据
    window.editUserData = async function(id) {
        try {
            const { data, error } = await supabase
                .from('hc_dnode_members')
                .select('*')
                .eq('id', id)
                .single();

            if (error) {
                throw error;
            }

            const modalTitle = document.getElementById('modal-title');
            const dataForm = document.getElementById('data-form');

            if (modalTitle) modalTitle.textContent = '编辑成员数据';
            if (dataForm) dataForm.reset();
            // 填充表单数据
            document.getElementById('dnode-id').value = data.dnode_id;
            document.getElementById('uu-id').value = data.id;
            document.getElementById('user-id').value=data.user_id;
            document.getElementById('role').value=data.role;
            document.getElementById('permissions').value=data.permissions ? JSON.stringify(data.permissions, null, 2) : '{}';


            dataModal.classList.remove('hidden');

        } catch (error) {
            console.error('加载用户数据错误:', error);
            showMessage(messageDiv, '加载数据失败: ' + error.message, 'error');
        }
    };

    // 确认删除
    window.confirmDelete = function(id) {
        document.getElementById('delete-data-id').value = id;
        deleteModal.classList.remove('hidden');
    };

    // 删除用户数据（逻辑删除）
    async function deleteUserData() {
        const dataId = document.getElementById('delete-data-id').value;
        const { data: userData, error: userError } = await supabase.auth.getUser();

        if (userError || !userData.user) {
            showMessage(messageDiv, '用户未登录', 'error');
            return;
        }

        try {
            setButtonLoading(confirmDeleteBtn, true);

            const { data, error } = await supabase
                .from('hc_dnode_members')
                .update({
                    is_deleted: true,
                    deleted_at: new Date().toISOString(),
                    deleted_by: userData.user.id
                })
                .eq('id', dataId)
                .select();

            if (error) {
                throw error;
            }

            if (data && data.length > 0) {
                closeDeleteModal();
                loadUserData();
                showMessage(messageDiv, '数据删除成功！', 'success');
            } else {
                throw new Error('删除失败：数据不存在或无权删除');
            }

        } catch (error) {
            console.error('删除用户数据错误:', error);
            showMessage(messageDiv, '删除失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(confirmDeleteBtn, false);
        }
    }

    // 检查用户登录状态并初始化
    async function initialize() {
        try {
            const { data: { session } } = await supabase.auth.getSession();

            if (session) {
                showUserInfo(session.user);
                loadUserData();
                // 获取URL参数对象
                const urlParams = new URLSearchParams(window.location.search);
                // 获取单个参数值
                document.getElementById('dnodesId').value = urlParams.get('uuid');

            } else {
                // 未登录，重定向到登录页面
                window.location.href = '../hc_login/index.html';
            }
        } catch (error) {
            console.error('初始化错误:', error);
            showMessage(messageDiv, '初始化失败: ' + error.message, 'error');
        }
    }

    // 初始化页面
    initialize();
    //回显组织
    getSelectById();
    //拿成员
    getProIdAndName();
    //拿角色
    getRoleAndName();
    /*  const select = document.getElementById('parent-id');
      select.onclick = function(a) {
          let aa =document.getElementById('parent-id').value;
          console.log('Select框被点击了');
      };*/
}